<?php

use com\gdl\kq\interfaces\AppAttendanceServiceIf;
use com\gdl\kq\dataobject\attendancegroup\AttendanceGroupDTO;
use com\gdl\common\dataobject\common\ResultDO;
date_default_timezone_set("PRC");
/**
 *  考勤
 *  @author gdl
 */
class api_AppAttendanceService extends api_Abstract implements AppAttendanceServiceIf
{
	
	
   //统计接口
    public function statisticsAppGet(AttendanceGroupDTO $attendancegroup){

        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";

        #接受参数

        $date = $data['date']?$data['date']:0;
        $userId = $data['userId']?$data['userId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($userId)){$result->message = "请选择用户"; return $result;}
        if(empty($date)){$result->message = "请选择日期"; return $result;}

        try{
            $recordings =  [
                'missCard'=>['num'=>0,'data'=>[]],//缺卡
                'late'=>['num'=>0,'data'=>[]], //迟到
                'leavEarly'=>['num'=>0,'data'=>[]],//早退
                'completion'=>['num'=>0,'data'=>[]],//旷工
                'onTime'=>['num'=>0,'data'=>[]],//准时
                'field'=>['num'=>0,'data'=>[]],//外勤
                'leave'=>['num'=>0,'data'=>[]],//请假
                'supCard'=>['num'=>0,'data'=>[]],//补卡申请
                'abnormal'=>['num'=>0,'data'=>[]],//异常记录
            ];
            //
//	$result->message = json_encode($data);
//       return $result;
            $tNum = date("t",strtotime($date));//选择日期的天数
            $start_time = strtotime(date('Y-m-01',strtotime($date)));  //获取本月第一天时间戳
            $array = array();
            for($i=0;$i<$tNum;$i++){
                $array[]= date('Y-m-d',$start_time+$i*86400); //每隔一天赋值给数组
            }
            if ($array){
                $array = implode("','",$array);
                $array = "'".$array."'";
            }else{
                $array = 1;
            }
            $attendancerecord = new model_attendance_attendancerecord();
            $leaverecordModel = new model_attendance_approvalprocessleaverecord();
            $replacementrecordModel = new model_attendance_approvalprocesscardreplacementrecord();
            $condition ="memberId = {$userId} and sureDate in ({$array}) ";
            $field = "sum(if(no=2,1,0)) as missCard,sum(if(leaveIn=2,1,0)) as `leave`,sum(if(no=3,1,0)) as supCard,sum(if((abnormalIdentityIs=2 or abnormalCoordinateIs=2),1,0)) as abnormal,sum(if(isGo=2,1,0)) as field,sum(if(abnormal=1,1,0)) as late,sum(if(abnormal=2,1,0)) as leavEarly,sum(if(absenteeism>=1,1,0)) as completion";
            $lists = $attendancerecord->selectOne($condition,$field);

            foreach ($recordings as $key=>$value){
                $onTimeList = [];
                if ($key=="onTime"){//
                    $onTimeList =  $attendancerecord->select(
                        " memberId = {$userId} and sureDate in ({$array}) and absenteeism=2 and abnormal=0 and no=1 and leaveIn=1",
                        "id,sureDate,sureTime,count(id) num"
                    )->items;
                    $recordings['onTime']['num'] = $onTimeList?$onTimeList[0]['num']:0;
                }else
                {
                    $recordings[$key]['num'] = $lists[$key];
                }
                $chiNum = array('七', '一', '二', '三', '四', '五', '六');
                $num = array(1=>"第一次",2=>"第二次",3=>"第三次");
                $baseTypes = array("上下班","上班","下班");
                $leaveTypes = array("事假","年假","事假","调休","产假","婚假","丧假");
                //获取记录列表
                switch ($key){
                        case 'missCard'://缺卡
                            if ($lists[$key]!=0){
                               $missCardList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and no=2",
                                    "id,sureDate,sureTime"
                                )->items;
                                foreach ($missCardList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                }
                                $recordings['missCard']['data'] = $missCardList?$missCardList:[];
                            }
                            break;
                        case 'late': //迟到
                            if ($lists[$key]!=0){
                                $lateList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and abnormal=1",
                                    "id,sureDate,sureTime,clockinTime"
                                )->items;
                                foreach ($lateList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                    $lateTime = $mC['clockinTime']-strtotime($mC['sureDate']." ".$mC['sureTime']);
                                    $mC['mark'] =  "上班迟到".gmdate("H小时i分钟",$lateTime);
                                }
                                $recordings['late']['data'] = $lateList?$lateList:[];
                            }
                            break;
                        case 'leavEarly'://早退
                            if ($lists[$key]!=0){
                                $leavEarlyList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and abnormal=2",
                                    "id,sureDate,sureTime,clockinTime"
                                )->items;
                                foreach ($leavEarlyList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                    $leavEarlyTime = strtotime($mC['sureDate']." ".$mC['sureTime'])-$mC['clockinTime'];
                                    $mC['mark'] =  "下班早退".gmdate("H小时i分钟",$leavEarlyTime);
                                }
                                $recordings['leavEarly']['data'] = $leavEarlyList?$leavEarlyList:[];
                            }
                            break;
                        case 'completion'://旷工
                            if ($lists[$key]!=0){
                                $completionList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and absenteeism>=1",
                                    "id,sureDate"
                                )->items;
                                foreach ($completionList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                }
                                $recordings['completion']['data'] = $completionList?$completionList:[];
                            }
                            break;
                        case 'onTime'://准时

                            foreach ($onTimeList as &$mC){
                                $week =  date('w',strtotime($mC['sureDate']));
                                $mC['week'] =  "星期".$chiNum[$week];
                            }
                            $recordings['onTime']['data'] = (!empty($onTimeList[0]['id']))?$onTimeList:[];
                            break;
                        case 'field'://外勤
                            if ($lists[$key]!=0){
                                $fieldList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and isGo=2",
                                    "id,sureDate,sureTime,clockinTime"
                                )->items;
                                foreach ($fieldList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                }
                                $recordings['field']['data'] = $fieldList?$fieldList:[];
                            }
                            break;
                        case 'leave'://请假
                            if ($lists[$key]!=0){
                                $leaveList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and leaveIn=2",
                                    "id,sureDate,sureTime,clockinTime,leaveInId"
                                )->items;
                                foreach ($leaveList as &$mC){
                                    $leaverecordInfo = $leaverecordModel->selectOne(
                                        " id = {$mC['leaveInId']}",
                                        " id leaverecordId,startTime,endTime,leaveType"
                                    );
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                    $mC['leaveType'] =  $leaverecordInfo?$leaveTypes[$leaverecordInfo['leaveType']]:"事假";
                                    $mC['leaveStartTime'] =  $leaverecordInfo['startTime'];
                                    $mC['leaveEndTime'] =  $leaverecordInfo['endTime'];
                                }
                                $recordings['leave']['data'] = $leaveList?$leaveList:[];
                            }
                            break;
                        case 'supCard'://补卡申请
                            if ($lists[$key]!=0){
                                $supCardList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and no=3",
                                    "id,sureDate,sureTime,clockinTime,noId"
                                )->items;
                                foreach ($supCardList as &$mC){
                                    $replacementrecordInfo = $replacementrecordModel->selectOne(
                                        " id = {$mC['noId']}",
                                        " id replaceMentRecordId,replacementTime,num,baseType"
                                    );
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                    $mC['replacementTime'] =  $replacementrecordInfo['replacementTime']."(".$num[$replacementrecordInfo['num']].$baseTypes[$replacementrecordInfo['baseType']].")";//补卡班次
                                }
                                $recordings['supCard']['data'] = $supCardList?$supCardList:[];
                            }
                            break;
                        case 'abnormal'://异常记录
                            if ($lists[$key]!=0){
                                $abnormalList =  $attendancerecord->select(
                                    " memberId = {$userId} and sureDate in ({$array}) and (abnormalIdentityIs=2 or abnormalCoordinateIs=2)",
                                    "id,sureDate,sureTime,abnormalIdentityIs,abnormalCoordinateIs,vioLationId,clockinCoordinate"
                                )->items;
                                foreach ($abnormalList as &$mC){
                                    $week =  date('w',strtotime($mC['sureDate']));
                                    $mC['week'] =  "星期".$chiNum[$week];
                                    if ($mC['abnormalIdentityIs']==2){
                                        $mark[] = "身份异常";
                                    }
                                    if ($mC['abnormalCoordinateIs']==2){
                                        $mC['clockinCoordinate'] =  unserialize($mC['clockinCoordinate']);
                                        $mark[] = "地点异常";
                                    }
                                    $mC['abnormalType'] =  implode(',',$mark);
                                    $mark = [];
                                }
                                $recordings['abnormal']['data'] = $abnormalList?$abnormalList:[];
                            }
                            break;
                }
            }
            $result->data = [[json_encode($recordings)]];
            $result->message ='成功';
            $result->code = 200;

        }catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }
    //获取人员每天的考勤租详细接口（包括选择日期是否为外勤）
    public function sbqAppGetUserDaysAttendanceGroupInfo(AttendanceGroupDTO $attendancegroup){

        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";

        #接受参数
        $platformId = $data['platformId']?$data['platformId']:0;
        $date = $data['date']?$data['date']:0;
        $userId = $data['userId']?$data['userId']:0;
        $unitId = $data['unitId']?$data['unitId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        #验证
        if(empty($userId)){$result->message = "请选择用户"; return $result;}
        if(empty($date)){$result->message = "请选择日期"; return $result;}

        try{
            $t = time();
            $today = date('Y-m-d',$t);
            $istoday = ($today==$date)?1:2;//1 今天 2 不是今天
            $undate = strtotime($date);//选择日期的时间戳
            $row = $this->getClockinRecordInfo($t,$undate,$userId,$platformId);
            if($row['code']=='200'){
                $status = $row['status'];////status 1 有考勤记录 2今天休息  3暂无排班
                $result->data = [['data'=>json_encode($row['data']),'status'=>$status]];
                $result->message = $row['msg'];
                $result->code = 200;
            }else{
                $result->message = $row['msg'];
            }

        }catch(Exception $e){
            $result->message = $e->getMessage();
        }

        return $result;
    }
    //
    public function sbqAppFaceRecognition(AttendanceGroupDTO $attendancegroup){
        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        return $result;
    }

    //添加身份验证记录
    public function addViolation(AttendanceGroupDTO $attendancegroup){

        $resultDO = new ResultDO();
        $data = $attendancegroup->data;

        try {
            $violationModel = new model_attendance_violation();
            $resultDO->code = 200;
            $resultDO->success = true;
            if (!$data['memberId']) {
                $resultDO->message = "信息不全,添加失败，请刷新再试!";
                return $resultDO;
            }
            $id = $violationModel->insert($data);

            ///////////////
            if ($id){
                $resultDO->message = '添加成功';
                $resultDO->message = $id;
                $resultDO->code = 200;
            }else{
                $resultDO->code = 400;
                $resultDO->message= 0;
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = 400;
        }
        return $resultDO;
    }

    //修改用户考勤记录的备注
    public function editAppUserRecordRemark(AttendanceGroupDTO $attendancegroup){

        $resultDO = new ResultDO();
        $data = $attendancegroup->data;

        try {
            $attendancerecordModel = new model_attendance_attendancerecord();
            $resultDO->code = 400;
            $resultDO->success = true;
            if (!$data['id']) {
                $resultDO->message = "信息不全,添加失败，请刷新再试!";
                return $resultDO;
            }
            $condition = " id = {$data['id']} and memberId={$data['memberId']}";
            $row = [
                'remark'=>$data['remark']
            ];
            $attendancerecordModel->update($condition,$row);

            ///////////////
            if ($data['id']){
                $resultDO->message = '修改成功';
                $resultDO->message = $data['id'];
                $resultDO->code = 200;
            }else{
                $resultDO->code = 400;
                $resultDO->message= 0;
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = 400;
        }
        return $resultDO;
    }

    //签到打卡接口
    public function sbqAppDoSignIn(AttendanceGroupDTO $attendancegroup){
        $resultDO = new ResultDO();
        $data = $attendancegroup->data;
        try {
            $attendancerecordModel = new model_attendance_attendancerecord();
            $resultDO->code = 400;
            $resultDO->success = true;
            if (!$data['memberId']) {
                $resultDO->message = "信息不全,添加失败，请刷新再试!";
                return $resultDO;
            }
            //判断用户是否存在考勤组中
            $attendancegroupModel = new model_attendance_attendancegroup();
            $attendancegroupJoin = ['atd_attendance_group_user as aagu'=>'atd_attendance_group.id=aagu.agId'];
            $attendancegroupRow = $attendancegroupModel->selectOne(
                " aagu.memberId={$data['memberId']} and aagu.type=1",
                "atd_attendance_group.*",
                "",
                "",
                $attendancegroupJoin);
            $date = date('Y-m-d',$data['time']);
            if (!$attendancegroupRow){
                $resultDO->message = "用户不存在考勤组!";
                return $resultDO;
            }else{
                $time         = $data['time'];//打卡时间戳
                $platformId         = $data['platformId'];//
                $memberId         = $data['memberId'];//会员ID
                $isRest         = $data['isRest'];//是否是休息日打卡
                $sureTime         = $data['sureTime'];//正常打卡时间点 ps:09:00:00
                $isGo         = $data['isGo'];//1正常考勤 2外勤打卡
                $remark         = $data['remark'];//备注
                $clockinNum         = $data['clockinNum'];//1第一次打卡  2第二次打卡  3第三次打卡
                $clockinType         = $data['clockinType'];//1上班打卡 2下班打卡
                //打卡地点 ['title'=>'重庆九龙坡智博中心','deviation'=>'500','coordinate'=>['lng'=>'106.459223','lat'=>'29.509867']]
                $clockinCoordinate         = unserialize($data['clockinCoordinate']);
                $coordinateSure         = unserialize($data['coordinateSure']);
                $abnormalCoordinateIs         = $data['abnormalCoordinateIs'];
                $vioLationId         = $data['vioLationId'];
                $abnormalIdentityIs         = $data['abnormalIdentityIs'];
                $photo         = unserialize($data['photo']);

                if ($photo){
                    $photo = implode(',',$photo);
                }else{
                    $photo = '';
                }
                $agId         = $attendancegroupRow['id'];//考勤组ID
                $agName         = $attendancegroupRow['title'];//考勤组名称
//                $goDaysNum     = unserialize($attendancegroupRow['goDaysNum']);//一天上班次数设置及其时间
                $offDutyOut    = $attendancegroupRow['offDutyOut'];//下班是否需要打卡 1打卡 2不打卡
                $faceStatus    = $attendancegroupRow['faceStatus'];//下班是否需要打卡 1打卡 2不打卡
                $unusualStatus = unserialize($attendancegroupRow['unusualStatus']);//异常定义 序列号数组
                $no = 1;//1正常打卡 2缺卡 3补卡 4请假
                $noId = 0;//当no字段为3时 是补卡记录ID 当no字段为4时 是请假记录ID
            }
            //查询当前时间和班次 是否已经正常打卡
            $y = $attendancerecordModel->selectOne(" sureDate='{$date}' and clockinNum = {$clockinNum} and clockinType = {$clockinType} and no =1 and memberId={$memberId}");
            if ($y){
                $resultDO->message = "已打卡，请勿重复打卡!";
                return $resultDO;
            }
            //判断用户是否请假 $sureTime $date
                //正常打卡时间戳
                $strtotimeSure = strtotime($date." ".$sureTime);
            $approvalprocessleaverecordModel = new model_attendance_approvalprocessleaverecord();
            $rrCondition = " memberId = {$memberId} and startTime <= '{$strtotimeSure}' and endTime>='{$strtotimeSure}' and status=2 ";
            $rrInfo = $approvalprocessleaverecordModel->selectOne($rrCondition);
            if ($rrInfo){
                $leaveIn = 2;
                $leaveInId = $rrInfo['id'];
            }else{
                $leaveIn = 1;
                $leaveInId = 0;
            }
            $absenteeism = 0;//0没有旷工 1旷工半天  2旷工1天
            $abnormal = 0;//1迟到 2早退

            //判断打卡时间有无旷工 迟到 sureTime(正常打卡时间点 ps:09:00:00) $time(打卡时间)
            $nowTime = strtotime($date." ".$sureTime);//记录正常时间点的时间戳
			if($isRest==1){//休息日不记入异常
				if ($clockinType==1){//1上班打卡 2下班打卡
					$beLate = $unusualStatus['beLate'];
					$beLateOne = $beLate[0]*60;
					$beLateTwo = $beLate[1]*60;
					if ($time>$nowTime){
						$abnormal = 1;
						$min = $time-$nowTime;
						if ($min>=$beLateOne && $min<$beLateTwo){
							$absenteeism = 1;
						}elseif($min>=$beLateTwo){
							$absenteeism = 2;
						}
					}
				}
				elseif ($clockinType==2 && $offDutyOut!=2){//18:00:00//是否需要下班卡 （1开启后，下班不打卡也不会记作异常）
					$leaveEarly = $unusualStatus['leaveEarly'];
					$leaveEarlyOne = $leaveEarly[0];
					$leaveEarlyTwo = $leaveEarly[1];
					if ($time<$nowTime){//早退
						$abnormal = 2;
						$min = $nowTime-$time;
						if ($min>=$leaveEarlyOne && $min<$leaveEarlyTwo){
							$absenteeism = 1;
						}elseif($min>=$leaveEarlyTwo){
							$absenteeism = 2;
						}
					}
				}
			}
            

            $dataIns = [
                'memberId'=>$memberId,
                'agId'=>$agId,
                'agName'=>$agName,
                'platformId'=>$platformId,
                'isGo'=>$isGo,
                'clockinType'=>$clockinType,
                'no'=>$no,
                'noId'=>$noId,
                'clockinNum'=>$clockinNum,
                'clockinTime'=>$time,
                'clockinDate'=>$date,
                'sureTime'=>$sureTime,
                'leaveIn'=>$leaveIn,
                'leaveInId'=>$leaveInId,
                'isRest'=>$isRest,
                'sureDate'=>$date,
                'faceStatus'=>$faceStatus,
                'vioLationId'=>$vioLationId,
                'abnormalIdentityIs'=>$abnormalIdentityIs,
                'abnormalCoordinateIs'=>$abnormalCoordinateIs,
                'clockinCoordinate'=>serialize($clockinCoordinate),
                'coordinate'=>serialize($coordinateSure),
                'remark'=>$remark,
//                'unusualRemark'=>serialize($unusualStatus),
                'photo'=>$photo,
                'abnormal'=>$abnormal,
                'absenteeism'=>$absenteeism,
            ];
            $id = $attendancerecordModel->insert($dataIns);

            ///////////////
            if ($id){
                $resultDO->message = '打卡成功';
//                $resultDO->data = [[$id]];
                $resultDO->code = 200;
            }else{
                $resultDO->code = 400;
                $resultDO->message= "打卡失败";
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = 400;
        }
        return $resultDO;

    }
    //查看打卡记录详细接口
    public function sbqAppSignInInfo(AttendanceGroupDTO $attendancegroup){

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->data = [];

        return $result;
    }
    private function getHi($second){
        $second = $second%(3600*24);
        $hour = floor($second/3600);
        $second = $second%3600;
        $minute = floor($second/60);
        // 不用管怎么实现的，能用就ok
        return $hour.':'.$minute;
    }

    // 获取选择日期的打卡信息
    /**
     * @param $t @@当天的时间戳
     * @param $undate @@选择日期的时间戳
     * @param $userId @@用户ID
     * @param $platformId @@平台ID
     */
    private function getClockinRecordInfo($t,$undate,$userId,$platformId){
        $return =['code'=>200,'data'=>[],'msg'=>"成功",'status'=>1];//status 1 有考勤记录 2今天休息  3暂无排班 4无需打卡 5无打卡记录
        $date = date('Y-m-d',$undate);
        //判断选择日期是否大于当天
        $startTime = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));//获取当天的0点时间戳
        $endTime = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));//获取当天的下午12点时间戳

        $globals = new service_globals();
        $attendancegroupModel = new model_attendance_attendancegroup();
        //查看用户选择的日期 记录
        $attendancerecordModel = new model_attendance_attendancerecord();
        $attendancegroupuserModel = new model_attendance_attendancegroupuser();

        //考勤组人员档案表
        $groupmemberrecordModel = new model_attendance_groupmemberrecord();
        //节假日定义方案表
        $setholidaysModel = new model_attendance_setholidays();

        //补卡记录Model
        $approvalprocesscardreplacementrecordModel = new model_attendance_approvalprocesscardreplacementrecord();
        //请假Model
        $approvalprocessleaverecordModel = new model_attendance_approvalprocessleaverecord();
            $recordCondition = " atd_attendance_record.memberId = {$userId} and sureDate='{$date}' ";
        $leftJoin = [
            'atd_violation as av'=>'atd_attendance_record.vioLationId=av.id'
        ];
        $recordInfos = $attendancerecordModel->select(
            $recordCondition,'atd_attendance_record.*','','',$leftJoin
        )->items;
        #记录END

        //获取用户考勤组 START
        $groupuserWhere = "atd_attendance_group_user.status=0 and atd_attendance_group_user.memberId={$userId} and aag.isdelete=0 ";
        $leftJoin = array(
            'atd_attendance_group as aag' => 'atd_attendance_group_user.agId=aag.id',
            'atd_setholidays as ass' => 'ass.id=aag.setholidaysId'
        );
        $groupFiled = "atd_attendance_group_user.id as groupUserId,atd_attendance_group_user.agId,aag.id as agId,aag.setholidaysId,aag.goDaysNum,aag.unusualStatus,aag.title as agName,aag.offDutyOut,aag.coordinate,aag.faceStatus,aag.trackLocation,ass.workday,ass.specialWorkday,ass.holiday";
        $groupuserRow = $attendancegroupuserModel->select(
            $groupuserWhere,
            $groupFiled,'','',
            $leftJoin)->items;
        $types = array_column($groupuserRow,'type');

        //获取用户考勤组 END
        if ($undate<$startTime){//历史考勤 查询记录 没有记录则显示补卡
            //查询用户当天是否需要打卡 考勤组人员档案表 根据档案表查询历史配置

            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("FIND_IN_SET('{$userId}',memberIds) and addTime<={$undate} order by id  desc");

            if (!$groupmemberrecordInfo && empty($groupuserRow[0]['agId'])){//当天没有班次添加
                $return['data'] = [];
                $return['status'] = 3;
                $return['msg'] = "暂无排班";
            }else{
                if ($groupmemberrecordInfo){
                    $workdayKey = unserialize($groupmemberrecordInfo['workday']);

                    $holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
                    //特殊工作日定义 [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
                    $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));

                    $goDaysNum     = unserialize($groupmemberrecordInfo['goDaysNum']);//一天上班次数设置及其时间
                    $unusualStatus     = unserialize($groupmemberrecordInfo['unusualStatus']);//一天上班次数设置及其时间
                }else{
                    $workdayKey = $groupuserRow[0]['workday'];
                    $holidayKey = $this->arrayDateToKey(unserialize($groupuserRow[0]['holiday']));
                    $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupuserRow[0]['specialWorkday']));
                    $goDaysNum     = unserialize($groupuserRow[0]['goDaysNum']);//一天上班次数设置及其时间
                    $unusualStatus     = unserialize($groupuserRow[0]['unusualStatus']);//一天上班次数设置及其时间
                }

                //获取日期是否是休息日 bool false是节假日  true不是节假日
                $isHolidaysAndFestivals = $globals->getDateIsHolidaysAndFestivals($date,$workdayKey,$holidayKey,$specialWorkdayKey);
//
//                if ($isHolidaysAndFestivals){//True 不是节假日 需要打卡

                    $num  = $goDaysNum?count($goDaysNum):1;
                    $isData = [
                        [],[],[],[],[],[]
                    ];
                    switch ($num){
                        case 1:
                            unset($isData[5]);
                            unset($isData[4]);
                            unset($isData[3]);
                            unset($isData[2]);
                            break;
                        case 2:
                            unset($isData[5]);
                            unset($isData[4]);
                            break;
                    }
                    //补充缺卡记录 暂时废弃 采用脚本t统一补卡
                    //$this->insertLackCard($recordInfos,$clockinNums,$agId,$userId);
                    //查找用户选择的日期是否补过卡
                    //查看当前班次是否有补卡记录‘’
                    foreach ($recordInfos as $key=>$value){
                        $aa['Id'] = $value['id'];
                        $aa['lackCard'] = 1;//1 正常记录  2 补卡记录 3缺卡记录 4请假记录
                        $noId = $value['noId'];
                        $aa['noId'] = $noId;
                        $aa['leaveIn'] = $value['leaveIn'];//1正常记录 2请假记录
                        $aa['leaveInId'] = $value['leaveInId'];//请假ID 默认为0
                        #基础 start
                        $aa['memberId'] = $userId;
                        $aa['agId'] = $value['agId'];
                        $aa['isGo'] = $value['isGo'];
                        if (!$isHolidaysAndFestivals){
                            $aa['isRest'] = 2;
                        }else{
                            $aa['isRest'] = 1;
                        }
                        $aa['faceStatus'] = $value['faceStatus'];
                        $aa['clockinNum'] = $value['clockinNum'];
                        $aa['clockinType'] = $value['clockinType'];
                        $aa['leaveIn'] = $value['leaveIn'];
                        $aa['remark'] = $value['remark']?$value['remark']:'';
                        $aa['abnormalCoordinateIs'] = $value['abnormalCoordinateIs'];
                        $aa['unusualRemark'] = empty($value['unusualRemark'])?"正常":$value['unusualRemark'];
                        $aa['sureTime'] = $value['sureTime'];//1迟到 2早退
                        $aa['absenteeism'] = $value['absenteeism'];//0没有旷工 1旷工半天  2旷工1天
                        $clockinCoordinate = unserialize($value['clockinCoordinate']);
                        $clockinCoordinate['title'] = $clockinCoordinate?$globals->format_html($clockinCoordinate['title']):"";
                        $aa['clockinCoordinate'] = $clockinCoordinate;
                        $aa['clockinCoordinateName'] = $clockinCoordinate?$clockinCoordinate['title']:'未知';
                        $aa['photo'] = empty($value['photo'])?[]:explode(',',$value['photo']);
                        $aa['clockinTime'] = $value['clockinTime'];
                        $aa['timeClockinHi'] = date('H:i',$value['clockinTime']);
                        $aa['abnormalIdentityIs'] = $value['abnormalIdentityIs'];
                        if ($value['abnormalIdentityIs']!=3){
                            $aa['abnormalIdentityIsTitle'] = ($aa['abnormalIdentityIs']==2)?"未通过":"已通过";
                        }else{
                            $aa['abnormalIdentityIsTitle'] = "未审核";
                        }
                        $aa['title'] = 3;
                        #基础 end
                        if ($value['isRest']!=2){
                            //1不是休息日 2休息日
                            if ($value['abnormal']==1){//1 迟到 2 早退
                                $aa['unusualRemark'] = str_replace('正常','',$aa['unusualRemark']);
                                $aa['unusualRemark'] = "迟到";
                                $aa['lackCardData'] = [
                                    'isType'=>2,//1 有补卡记录 2没有补卡记录
                                    'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                                    'doTime'=>0,//打卡时间
                                ];
                            }
                            if ($value['abnormal']==2){//1 迟到 2 早退
                                $aa['unusualRemark'] = str_replace('正常','',$aa['unusualRemark']);
                                $aa['unusualRemark'] = "早退";
                                $aa['lackCardData'] = [
                                    'isType'=>2,//1 有补卡记录 2没有补卡记录
                                    'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                                    'doTime'=>0,//打卡时间
                                ];
                            }
                            if ($value['absenteeism']>=1){
                                $aa['unusualRemark'] = str_replace('早退','',$aa['unusualRemark']);
                                $aa['unusualRemark'] = str_replace('迟到','',$aa['unusualRemark']);
                                $aa['unusualRemark'] = "旷工";
								$aa['lackCardData'] = [
                                    'isType'=>2,//1 有补卡记录 2没有补卡记录
                                    'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                                    'doTime'=>0,//打卡时间
                                ];

                            }
                            //1正常打卡 2缺卡 3补卡
                            if ($value['no']==2 || $value['no']==3){//这个班次缺卡了或已经补卡
                                $rrCondition = " id = {$noId} ";
                                $rrInfo = $approvalprocesscardreplacementrecordModel->selectOne($rrCondition);
                                $aa['lackCard'] = $value['no'];//1 正常记录  2缺卡记录  3补卡记录
                                $aa['unusualRemark'] = $value['no']==3?"补卡":"缺卡";
                                $aa['lackCardData'] = [
                                    'isType'=>$rrInfo?1:2,//1 有补卡记录 2没有补卡记录
                                    'isDoSure'=>$rrInfo?$rrInfo['status']:4,//1审核中 2审核通过 3未通过 4撤销
                                    'doTime'=>$rrInfo?date('H:s',$rrInfo['time']):'',//打卡时间
                                ];
                            }else{//这个班次正常打卡
                                $aa['abnormalIdentityIs'] = $value['abnormalIdentityIs'];
                                if ($value['abnormalIdentityIs']!=3){
                                    $aa['abnormalIdentityIsTitle'] = ($aa['abnormalIdentityIs']==2)?"未通过":"已通过";
                                }else{
                                    $aa['abnormalIdentityIsTitle'] = "未审核";
                                }
                            }
                        }

                        if ($value['isGo']==2){//1正常考勤 2外勤打卡
                            $aa['unusualRemark'] .= ",外勤";
                            $isGoRow = $this->appUserIsOutGo($userId,$platformId,$value['sureTime'],$value['sureDate']);
                            $aa['outgoRecordId'] = $isGoRow?$isGoRow['id']:0;
                        }

                        if ($value['leaveIn']==2){//这个班次请假了
                            $aa['unusualRemark'] = "请假";
                        }
                        $ss = 0;
                        if ($value['clockinNum']==1 && $value['clockinType']==1){
                            $ss = 0;
                        }elseif ($value['clockinNum']==1 && $value['clockinType']==2){
                            $ss = 1;
                        }elseif ($value['clockinNum']==2 && $value['clockinType']==1){
                            $ss = 2;
                        }elseif ($value['clockinNum']==2 && $value['clockinType']==2){
                            $ss = 3;
                        }elseif ($value['clockinNum']==3 && $value['clockinType']==1){
                            $ss = 4;
                        }elseif ($value['clockinNum']==3 && $value['clockinType']==2){
                            $ss = 5;
                        }
                        $isData[$ss] = $aa;
                    }
//                }
//                else{
//                    //是休息日 2018 07 18 统计休息日打卡
//
//                    $return['data'] = [];
//                    $return['status'] = 2;
//                    $return['msg'] = "今天休息日";
//                }
                $yData = [
                    'time'=>time(),
                    'agId'=>$groupmemberrecordInfo['agId'],
                    'agName'=>$groupmemberrecordInfo['agName'],
                    'lackCard'=>1,//1 正常记录  2缺卡记录  3补卡记录
                    'leaveIn'=>1,//1正常记录 2请假记录
                    'leaveInId'=>0,//请假ID 默认为0
                    'isGo'=>1,//请假ID 默认为0
                    'unusualRemark'=>'正常',//异常记录
                    'lackCardData'=>[
                                    'isType'=>2,//1 有补卡记录 2没有补卡记录
                                    'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                                    'doTime'=>0,//打卡时间
                                ],//迟到或者请假的记录
                ];
                $insertRecordData = [
                    'memberId'=>$userId,
                    'agName'=>$groupmemberrecordInfo['agName'],
                    'agId'=>$groupmemberrecordInfo['agId']
                ];
                if (isset($isData[0]) && empty($isData[0])){
                    $one = $yData;
                    $one['clockinType'] = 1;
                    $one['clockinNum'] = 1;
                    $one['sureTime'] = $goDaysNum[0]['startTime'];
                    //添加判断有无添加缺卡记录
                    $recordS = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=1 and no=2");
                    if (!$recordS){
                        $insertRecordData['sureTime'] = $goDaysNum[0]['startTime'];
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['clockinNum']= 1;
                        $insertRecordData['clockinType']= 1;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $one;
                    $yesData['Id'] = $recordS?$recordS['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;//1 正常记录  2缺卡记录 3补卡记录  4请假记录
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[0] = $yesData;
                }
                if (isset($isData[1]) && empty($isData[1])){
                    $two = $yData;
                    $two['clockinType'] = 2;
                    $two['clockinNum'] = 1;
                    $two['sureTime'] = $goDaysNum[0]['endTime'];
                    $oneRcord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=2 and no=2");
                    //添加判断有无添加缺卡记录
                    if (!$oneRcord){
                        $insertRecordData['sureTime'] = $goDaysNum[0]['endTime'];
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['clockinNum']= 1;
                        $insertRecordData['clockinType']= 2;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $two;
                    $yesData['Id'] = $oneRcord?$oneRcord['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;//1 正常记录  2缺卡记录  3补卡记录
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[1] = $yesData;

                }
                if (isset($isData[2]) && empty($isData[2])){
                    $three = $yData;
                    $three['clockinType'] = 1;//第二次上班卡
                    $three['clockinNum'] = 2;
                    $three['sureTime'] = $goDaysNum[1]['startTime'];
                    $twoRecord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=1 and no=2");
                    //添加判断有无添加缺卡记录
                    if (!$twoRecord){
                        $insertRecordData['sureTime'] = $goDaysNum[1]['startTime'];
                        $insertRecordData['clockinNum']= 2;
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['clockinType']= 1;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $three;
                    $yesData['Id'] = $twoRecord?$twoRecord['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[2] = $yesData;
                }
                if (isset($isData[3]) && empty($isData[3])){
                    $four = $yData;
                    $four['clockinType'] = 2;
                    $four['clockinNum'] = 2;
                    $four['sureTime'] = $goDaysNum[1]['endTime'];
                    //判断第二次上班卡有无打卡
                    $twoRecord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=2 and no=2");
                    //添加判断有无添加缺卡记录
                    if (!$twoRecord){
                        $insertRecordData['sureTime'] = $goDaysNum[1]['endTime'];
                        $insertRecordData['clockinNum']= 2;
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['clockinType']= 2;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $four;
                    $yesData['Id'] = $twoRecord?$twoRecord['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[3] = $yesData;
                }
                if (isset($isData[4]) && empty($isData[4])){
                    $five = $yData;
                    $five['clockinType'] = 1;
                    $five['clockinNum'] = 3;
                    $five['sureTime'] = $goDaysNum[2]['startTime'];
                    //添加判断有无添加缺卡记录
                    if ($fiveRecordS = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=3 and clockinType=1 and no=2")){
                        $insertRecordData['sureTime'] = $goDaysNum[2]['startTime'];
                        $insertRecordData['clockinNum']= 3;
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['clockinType']= 1;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $five;
                    $yesData['Id'] = $fiveRecordS?$fiveRecordS['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[4] = $yesData;
                }
                if (isset($isData[5]) && empty($isData[5])){
                    $six = $yData;
                    $six['clockinType'] = 2;
                    $six['clockinNum'] = 3;
                    $six['sureTime'] = $goDaysNum[2]['endTime'];
                    //添加判断有无添加缺卡记录
                    if ($sixRecordS = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=3 and clockinType=2 and no=2")){
                        $insertRecordData['clockinNum']= 3;
                        $insertRecordData['sureTime'] = $goDaysNum[2]['endTime'];
                        $insertRecordData['clockinType']= 2;
                        $insertRecordData['sureDate'] = $date;
                        $insertRecordData['no']= 2;
                        $id = $attendancerecordModel->insert($insertRecordData);
                    }
                    $yesData = $six;
                    $yesData['Id'] = $sixRecordS?$sixRecordS['id']:$id;
                    $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $yesData['lackCard'] = 2;
                    $yesData['unusualRemark'] = "缺卡";
                    $yesData['lackCardData'] = [
                        'isType'=>2,//1 有补卡记录 2没有补卡记录
                        'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                    ];
                    $isData[5] = $yesData;
                }
                if (!$isHolidaysAndFestivals){
                    $return['status'] = 2;
                }else{
                    $return['status'] = 1;
                }
                $return['data'] = $isData;
            }
        }elseif ($undate>=$startTime && $undate<=$endTime){//选择日期为当天
            if (empty($groupuserRow)){//该用户处于无需考勤人员组中
                $return['code'] = 200;
                $return['status'] = 4;
                $return['msg'] = "该用户没有考勤组,不需要打卡！";

            }elseif (count($groupuserRow)>=2 || in_array(2,$types)){
                $return['code'] = 200;
                $return['status'] = 4;
                $return['msg'] = "该用户不需要打卡！";
            }else{
                $agId         = $groupuserRow[0]['agId'];//考勤组ID
                $agName         = $groupuserRow[0]['agName'];//考勤组名称
                $setholidaysId         = $groupuserRow[0]['setholidaysId'];//考勤组名称
                $goDaysNum     = unserialize($groupuserRow[0]['goDaysNum']);//一天上班次数设置及其时间
                $offDutyOut    = $groupuserRow[0]['offDutyOut'];//下班是否需要打卡 1打卡 2不打卡 （开启后，下班不打卡也不会记作异常）
                $coordinate    = unserialize($groupuserRow[0]['coordinate']);//签到点坐标 多维数组序列化保存
                $faceStatus    = $groupuserRow[0]['faceStatus'];//是否开启人脸 1开启 2不开启
                $trackLocation = $groupuserRow[0]['trackLocation'];//1 不开启轨迹定位 2 开启轨迹定位
                $unusualStatus = unserialize($groupuserRow[0]['unusualStatus']);//异常定义 序列号数组

                //获取日期是否是休息日 bool false是节假日  true不是节假日
                $setholidaysRow = $setholidaysModel->selectOne(" id = {$setholidaysId} ",'workday,specialWorkday,holiday');//查询节假日定义
                if ($setholidaysRow){
                    $workdayKey = unserialize($setholidaysRow['workday']);
                    $specialWorkdayKey = $this->arrayDateToKey(unserialize($setholidaysRow['specialWorkday']));
                    $holidayKey = $this->arrayDateToKey(unserialize($setholidaysRow['holiday']));
                }else{
                    $workdayKey = [];
                    $specialWorkdayKey = [];
                    $holidayKey = [];
                }
                $isHolidaysAndFestivals = $globals->getDateIsHolidaysAndFestivals($date,$workdayKey,$holidayKey,$specialWorkdayKey);
                $isRest = 1;//1不是休息日 2休息日
                if (!$isHolidaysAndFestivals){
                    $return['status'] = 2;
                    //是休息日 2018 07 18 统计休息日打卡
                    $isRest = 2;
                }
                foreach ($coordinate as &$as){
//                    $as['faceStatus'] = $faceStatus;
                    $as['isGo'] = 1;
                }
                //获取公共考勤地点
               $apppublicarea = new model_attendance_apppublicarea();
               $apppublicareaList = $apppublicarea->select(" platformId={$platformId} ",'title,deviation,coordinate')->items;
                foreach ($apppublicareaList as &$a){
                    $a['coordinate'] = unserialize($a['coordinate']);
                    $a['isGo'] = 3;//1正常 2外勤 3公共
                }
                $coordinate = array_merge($coordinate,$apppublicareaList);

                $num  = $goDaysNum?count($goDaysNum):1;
                $isData = [
                    [],[],[],[],[],[]
                ];
                switch ($num){
                    case 1:
                        unset($isData[5]);
                        unset($isData[4]);
                        unset($isData[3]);
                        unset($isData[2]);
                        break;
                    case 2:
                        unset($isData[5]);
                        unset($isData[4]);
                        break;
                }

                //获取当前时间之前的打卡记录
                foreach ($recordInfos as $key=>$value) {
                    $aa['Id'] = $value['id'];//
                    $aa['lackCard'] = 1;//1 正常记录  2 补卡记录 3缺卡记录 4请假记录
                    $noId = $value['noId'];
                    $aa['noId'] = $noId;
                    $aa['isRest'] = $isRest;
                    $aa['lackCardData'] = [];
                    #基础 start
                        $aa['sure'] = 1;//1有记录 2没有记录
                        $aa['memberId'] = $userId;
                        $aa['agId'] = $value['agId'];
                        $aa['faceStatus'] = $value['faceStatus'];
                        $aa['leaveIn'] = $value['leaveIn'];//1正常记录 2请假记录
                        $aa['leaveInId'] = $value['leaveInId'];//请假ID 默认为0
                        $aa['clockinType'] = $value['clockinType'];
                        $aa['abnormalCoordinateIs'] = $value['abnormalCoordinateIs'];
                        $aa['isGo'] = $value['isGo'];
                        $aa['no'] = $value['no'];
                        $aa['clockinNum'] = $value['clockinNum'];
                        $aa['remark'] = $value['remark']?$value['remark']:'';
                        $aa['abnormalIdentityIs'] = $value['abnormalIdentityIs'];
                        if ($value['abnormalIdentityIs']!=3){
                            $aa['abnormalIdentityIsTitle'] = ($aa['abnormalIdentityIs']==2)?"未通过":"已通过";
                        }else{
                            $aa['abnormalIdentityIsTitle'] = "未审核";
                        }
                        $aa['unusualRemark'] = empty($value['unusualRemark'])?"正常":$value['unusualRemark'];
                        $aa['clockinTime'] = $value['clockinTime'];
                        $aa['photo'] = empty($value['photo'])?[]:explode(',',$value['photo']);
                        $aa['timeClockinHi'] = $value['clockinTime']?date('H:i',$value['clockinTime']):'';
                        $clockinCoordinate = unserialize($value['clockinCoordinate']);
                        $clockinCoordinate['title'] = $clockinCoordinate?$globals->format_html($clockinCoordinate['title']):"";
                        $aa['clockinCoordinate'] = $clockinCoordinate;
                        $aa['clockinCoordinateName'] = $clockinCoordinate?$clockinCoordinate['title']:'未知';
                    $aa['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                    $aa['sureTime'] = $value['sureTime'];//1迟到 2早退
                    $aa['absenteeism'] = $value['absenteeism'];//0没有旷工 1旷工半天  2旷工1天
                    #基础 end
                    if ($value['abnormal']==1){//1 迟到 2 早退
                        $aa['unusualRemark'] = str_replace('正常','',$aa['unusualRemark']);
                        $aa['unusualRemark'] = "迟到";
                        $aa['lackCardData'] = [
                            'isType'=>2,//1 有补卡记录 2没有补卡记录
                            'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                            'doTime'=>0,//打卡时间
                        ];
                    }
                    if ($value['abnormal']==2){//1 迟到 2 早退
                        $aa['unusualRemark'] = str_replace('正常','',$aa['unusualRemark']);
                        $aa['unusualRemark'] = "早退";
                        $aa['lackCardData'] = [
                            'isType'=>2,//1 有补卡记录 2没有补卡记录
                            'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                            'doTime'=>0,//打卡时间
                        ];
                    }
                    if ($value['absenteeism']>=1){
                        $aa['unusualRemark'] = str_replace('早退','',$aa['unusualRemark']);
                        $aa['unusualRemark'] = str_replace('迟到','',$aa['unusualRemark']);
                        $aa['unusualRemark'] = "旷工";
						$aa['lackCardData'] = [
                            'isType'=>2,//1 有补卡记录 2没有补卡记录
                            'isDoSure'=>0,//1审核中 2审核通过 3未通过 4撤销
                            'doTime'=>0,//打卡时间
                        ];
                    }
                    //1正常打卡 2缺卡 3补卡
                    if ($value['no']==2 || $value['no']==3){//这个班次缺卡了或已经补卡
                        $rrCondition = " id = {$noId} ";
                        $rrInfo = $approvalprocesscardreplacementrecordModel->selectOne($rrCondition);
                        $aa['lackCard'] = $value['no'];//1 正常记录  2缺卡记录  3补卡记录
                        $aa['unusualRemark'] = $value['no']==3?"补卡":"缺卡";
                        $aa['lackCardData'] = [
                            'isType'=>$rrInfo?1:2,//1 有补卡记录 2没有补卡记录
                            'isDoSure'=>$rrInfo?$rrInfo['status']:4,//1审核中 2审核通过 3未通过 4撤销
                            'doTime'=>$rrInfo?date('H:s',$rrInfo['time']):'',//打卡时间
                        ];
                    }
                    else{//这个班次正常打卡
                        $aa['clockinTime'] = $value['clockinTime'];
                        $aa['timeClockinHi'] = date('H:i',$value['clockinTime']);
                        $aa['abnormalIdentityIs'] = $value['abnormalIdentityIs'];
                        if ($value['abnormalIdentityIs']!=3){
                            $aa['abnormalIdentityIsTitle'] = ($aa['abnormalIdentityIs']==2)?"未通过":"已通过";
                        }else{
                            $aa['abnormalIdentityIsTitle'] = "未审核";
                        }
                    }

                    if ($value['isGo']==2){//1正常考勤 2外勤打卡
                        $aa['unusualRemark'] .= ",外勤";
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$value['sureTime'],$value['sureDate']);
                        $aa['outgoRecordId'] = $isGoRow?$isGoRow['id']:0;
                    }
                    if ($value['leaveIn']==2){//这个班次请假了
//                        $ssCondition = " id = {$value['leaveInId']} ";
//                        $ssInfo = $approvalprocessleaverecordModel->selectOne($ssCondition);
                        $aa['unusualRemark'] = "请假";
                    }
                    $ss = 0;

                    if ($value['clockinNum']==1 && $value['clockinType']==1){
                        $ss = 0;
                    }elseif ($value['clockinNum']==1 && $value['clockinType']==2){
                        $ss = 1;
                    }elseif ($value['clockinNum']==2 && $value['clockinType']==1){
                        $ss = 2;
                    }elseif ($value['clockinNum']==2 && $value['clockinType']==2){
                        $ss = 3;
                    }elseif ($value['clockinNum']==3 && $value['clockinType']==1){
                        $ss = 4;
                    }elseif ($value['clockinNum']==3 && $value['clockinType']==2){
                        $ss = 5;
                    }

                    $isData[$ss] = $aa;
                }
                $yData = [
                    'time'=>time(),
                    'coordinate'=>$coordinate,
                    'agId'=>$agId,
                    'isRest'=>$isRest,
                    'agName'=>$agName,
                    'isGo'=>1,
                    'lackCard'=>1,//1 正常记录  2缺卡记录  3补卡记录
                    'leaveIn'=>1,//1正常记录 2请假记录
                    'leaveInId'=>0,//请假ID 默认为0
                    'unusualRemark'=>'正常',//异常记录
                    'lackCardData'=>[],//迟到或者请假的记录
                    'trackLocation'=>$trackLocation,
                    'faceStatus'=>$faceStatus,
                ];
                $insertRecordData = [
                    'memberId'=>$userId,
                    'agName'=>$agName,
                    'agId'=>$agId
                ];


//                判断当前时间 是在哪一个打卡段
                if (isset($goDaysNum[0]['startTime'])){
                    $onegoDaysStartTime = strtotime($date." ".$goDaysNum[0]['startTime']);
                }
                if (isset($goDaysNum[0]['endTime'])){
                    $onegoDaysEndTime = strtotime($date." ".$goDaysNum[0]['endTime']);
                }
                if (isset($goDaysNum[1]['startTime'])){
                    $twogoDaysStartTime = strtotime($date." ".$goDaysNum[1]['startTime']);
                }
                if (isset($goDaysNum[1]['endTime'])){
                    $twogoDaysEndTime = strtotime($date." ".$goDaysNum[1]['endTime']);
                }
                if (isset($goDaysNum[2]['startTime'])){
                    $threegoDaysStartTime =strtotime($date." ".$goDaysNum[2]['startTime']);
                }
                if (isset($goDaysNum[2]['endTime'])){
                    $threegoDaysEndTime = strtotime($date." ".$goDaysNum[2]['endTime']);
                }
                $o = true;

                if (isset($isData[0]) && empty($isData[0])){
                    $one = $yData;
                    $one['clockinType'] = 1;
                    $one['clockinNum'] = 1;
                    $one['sureTime'] = $goDaysNum[0]['startTime'];
                    //判断时间是否在第一次上班打卡时间段
                    if ($t<$onegoDaysEndTime){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$one['sureTime']);
                        if ($isGoRow){
                            $one['isGo'] = 2;// id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,//1正常 2外勤 3公共
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $one['coordinate'] = array_merge($one['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $one['isGo'] = 1;
//                        }
                        $one['title'] = 1;//1 上班打卡 2还未到打卡时间
                        $isData[0] = $one;
                    }else{
                        //添加判断有无添加缺卡记录
                        $recordS = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=1 and no=2");
                        if (!$recordS){
                            $insertRecordData['sureTime'] = $goDaysNum[0]['startTime'];
                            $insertRecordData['sureDate'] = $date;
                            $insertRecordData['clockinNum']= 1;
                            $insertRecordData['clockinType']= 1;
                            $insertRecordData['no']= 2;
                            $attendancerecordModel->insert($insertRecordData);
                        }
                        $yesData = $one;
                        $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                        $yesData['lackCard'] = 2;//1 正常记录  2缺卡记录 3补卡记录  4请假记录
                        $yesData['unusualRemark'] = "缺卡";
                        $yesData['lackCardData'] = [
                            'isType'=>2,//1 有补卡记录 2没有补卡记录
                            'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                        ];
                        $isData[0] = $yesData;

                    }
                }
                if (isset($isData[1]) && empty($isData[1])){
                    $two = $yData;
                    $two['clockinType'] = 2;
                    $two['clockinNum'] = 1;
                    $two['sureTime'] = $goDaysNum[0]['endTime'];
                    //判断第一次上班卡有无记录
                    $GoOneStart = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=1");

                    //判断时间是否在第一次下班打卡时间段
                    if ($GoOneStart && $t>=$onegoDaysStartTime && (isset($twogoDaysStartTime)?($t<$twogoDaysStartTime):1)){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$two['sureTime']);
                        if ($isGoRow){
                            $two['isGo'] = 2;//1正常考勤 2外勤打卡 id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $two['coordinate'] = array_merge($two['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $two['isGo'] = 1;
//                        }
                        $two['title'] = 1;//1 上班打卡 2还未到打卡时间
                        $isData[1] = $two;
                    }else{
                        $oneRcord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=2 and no=2");
                        if ($t<$onegoDaysEndTime && !$oneRcord){//还未到打卡时间 当前时间小于 第二次打卡上班开始时间
                            $two['title'] = 2;//1 上班打卡 2还未到打卡时间
                            $isData[1] = $two;
                        }else{
                            //添加判断有无添加缺卡记录
                            if (!$oneRcord){
                                $insertRecordData['sureTime'] = $goDaysNum[0]['endTime'];
                                $insertRecordData['sureDate'] = $date;
                                $insertRecordData['clockinNum']= 1;
                                $insertRecordData['clockinType']= 2;
                                $insertRecordData['no']= 2;
                                $attendancerecordModel->insert($insertRecordData);
                            }
                            $yesData = $two;
                            $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                            $yesData['lackCard'] = 2;
                            $yesData['unusualRemark'] = "缺卡";
                            $yesData['lackCardData'] = [
                                'isType'=>2,//1 有补卡记录 2没有补卡记录
                                'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                            ];
                            $isData[1] = $yesData;
                        }

                    }
                }
                if (isset($isData[2]) && empty($isData[2])){
                    $three = $yData;
                    $three['clockinType'] = 1;//第二次上班卡
                    $three['clockinNum'] = 2;
                    $three['sureTime'] = $goDaysNum[1]['startTime'];
                    //判断第一次下班卡有无打卡
                    $GoOneDown = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=1 and clockinType=2");

                    //判断时间是否在第二次上班打卡时间段
                    if ($GoOneDown && $t>=$onegoDaysEndTime && $t<$twogoDaysEndTime){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$three['sureTime']);
                        if ($isGoRow){
                            $three['isGo'] = 2;//1正常考勤 2外勤打卡 id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $three['coordinate'] = array_merge($three['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $three['isGo'] = 1;
//                        }
                        $three['title'] = 1;
                        $isData[2] = $three;
                    }else{
                        $twoRecord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=1 and no=2");
                        if ($t<$onegoDaysEndTime && !$twoRecord){//还未到打卡时间 选中时间小于 第三次打卡上班开始时间
                            $three['title'] = 2;
                            $isData[2] = $three;
                        }else{
                            //添加判断有无添加缺卡记录
                            if (!$twoRecord){
                                $insertRecordData['sureTime'] = $goDaysNum[1]['startTime'];
                                $insertRecordData['clockinNum']= 2;
                                $insertRecordData['sureDate'] = $date;
                                $insertRecordData['clockinType']= 1;
                                $insertRecordData['no']= 2;
                                $attendancerecordModel->insert($insertRecordData);
                            }
                            $yesData = $three;
                            $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                            $yesData['lackCard'] = 2;
                            $yesData['unusualRemark'] = "缺卡";
                            $yesData['lackCardData'] = [
                                'isType'=>2,//1 有补卡记录 2没有补卡记录
                                'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                            ];
                            $isData[2] = $yesData;
                        }
                    }
                }
                if (isset($isData[3]) && empty($isData[3])){
                    $four = $yData;
                    $four['clockinType'] = 2;
                    $four['clockinNum'] = 2;
                    $four['sureTime'] = $goDaysNum[1]['endTime'];
                    //判断第二次上班卡有无打卡
                    $twoGoUp = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=1");

                    //判断时间是否在第二次下班打卡时间段
                    if ($twoGoUp && $t>=$twogoDaysStartTime && (isset($threegoDaysStartTime)?($t<$threegoDaysStartTime):1)){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$four['sureTime']);
                        if ($isGoRow){
                            $four['isGo'] = 2;//1正常考勤 2外勤打卡 id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $four['coordinate'] = array_merge($four['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $four['isGo'] = 1;
//                        }
                        $four['title'] = 1;
                        $isData[3] = $four;
                    }else{
                        $twoRecord = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=2 and no=2");

                        if ($t<$twogoDaysEndTime && !$twoRecord){//还未到打卡时间 当前时间小于 第一次打卡下班开始时间
                            $four['title'] = 2;
                            $isData[3] = $four;
                        }else{
                            //添加判断有无添加缺卡记录
                            if (!$twoRecord){
                                $insertRecordData['sureTime'] = $goDaysNum[1]['endTime'];
                                $insertRecordData['clockinNum']= 2;
                                $insertRecordData['sureDate'] = $date;
                                $insertRecordData['clockinType']= 2;
                                $insertRecordData['no']= 2;
                                $attendancerecordModel->insert($insertRecordData);
                            }
                            $yesData = $four;
                            $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                            $yesData['lackCard'] = 2;
                            $yesData['unusualRemark'] = "缺卡";
                            $yesData['lackCardData'] = [
                                'isType'=>2,//1 有补卡记录 2没有补卡记录
                                'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                            ];
                            $isData[3] = $yesData;
                        }

                    }
                }
                if (isset($isData[4]) && empty($isData[4])){
                    $five = $yData;
                    $five['clockinType'] = 1;
                    $five['clockinNum'] = 3;
                    $five['sureTime'] = $goDaysNum[2]['startTime'];
                    //判断第二次下班卡有无记录
                    $GoTwoDown = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=2 and clockinType=2");

                    //判断时间是否在第三次上班打卡时间段
                    if ($GoTwoDown && $t>=$twogoDaysEndTime && $t<$threegoDaysEndTime){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$five['sureTime']);
                        if ($isGoRow){
                            $five['isGo'] = 2;//1正常考勤 2外勤打卡 id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $five['coordinate'] = array_merge($five['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $five['isGo'] = 1;
//                        }
                        $five['title'] = 1;
                        $isData[4] = $five;
                    }else{
                        if ($t<$twogoDaysEndTime){//还未到打卡时间 当前时间小于 第三次打卡上班开始时间
                            $five['title'] = 2;
                            $isData[4] = $five;
                        }else{
                            //添加判断有无添加缺卡记录
                            if ($attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=3 and clockinType=1 and no=2")){
                                $insertRecordData['sureTime'] = $goDaysNum[2]['startTime'];
                                $insertRecordData['clockinNum']= 3;
                                $insertRecordData['sureDate'] = $date;
                                $insertRecordData['clockinType']= 1;
                                $insertRecordData['no']= 2;
                                $attendancerecordModel->insert($insertRecordData);
                            }
                            $yesData = $five;
                            $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                            $yesData['lackCard'] = 2;
                            $yesData['unusualRemark'] = "缺卡";
                            $yesData['lackCardData'] = [
                                'isType'=>2,//1 有补卡记录 2没有补卡记录
                                'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                            ];
                            $isData[4] = $yesData;
                        }

                    }
                }
                if (isset($isData[5]) && empty($isData[5])){
                    $six = $yData;
                    $six['clockinType'] = 2;
                    $six['clockinNum'] = 3;
                    $six['sureTime'] = $goDaysNum[2]['endTime'];
                    //判断第二次下班卡有无记录
                    $GoThreeUp = $attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=3 and clockinType=1");

                    //判断时间是否在第三次下班打卡时间段
                    if ($GoThreeUp && $t>=$threegoDaysStartTime){//还在打卡时段
                        $isGoRow = $this->appUserIsOutGo($userId,$platformId,$six['sureTime']);
                        if ($isGoRow){
                            $six['isGo'] = 2;//1正常考勤 2外勤打卡 id,address,lng,lat,radius deviation
                            $isGoCoordinate = [
                                'title'=>$isGoRow['address'],
                                'deviation'=>$isGoRow['deviation'],
                                'isGo'=>2,
                                'coordinate'=>['lng'=>$isGoRow['lng'],'lat'=>$isGoRow['lat']]
                            ];
                            $six['coordinate'] = array_merge($six['coordinate'],[$isGoCoordinate]);
                        }
//                        else{
//                            $six['isGo'] = 1;
//                        }
                        $six['title'] = 1;
                        $isData[5] = $six;
                    }else{
                        if ($t<$threegoDaysEndTime){//还未到打卡时间 选中时间小于 第三次打卡上班开始时间
                            $six['title'] = 2;
                            $isData[5] = $six;
                        }else{
                            //添加判断有无添加缺卡记录
                            if ($attendancerecordModel->selectOne(" memberId= {$userId} and sureDate='{$date}' and clockinNum=3 and clockinType=2 and no=2")){
                                $insertRecordData['clockinNum']= 3;
                                $insertRecordData['sureTime'] = $goDaysNum[2]['endTime'];
                                $insertRecordData['clockinType']= 2;
                                $insertRecordData['sureDate'] = $date;
                                $insertRecordData['no']= 2;
                                $attendancerecordModel->insert($insertRecordData);
                            }
                            $yesData = $six;
                            $yesData['title'] = 3;//1 上班打卡 2还未到打卡时间 3已过打卡时间
                            $yesData['lackCard'] = 2;
                            $yesData['unusualRemark'] = "缺卡";
                            $yesData['lackCardData'] = [
                                'isType'=>2,//1 有补卡记录 2没有补卡记录
                                'isDoSure'=>4,//1审核中 2审核通过 3未通过 4撤销
                            ];
                            $isData[5] = $yesData;
                        }
                    }
                }
                if (!$isHolidaysAndFestivals){
                    $return['status'] = 2;
                }else{
                    $return['status'] = 1;
                }
                $return['data'] = $isData;
            }

        }else{//选择日期为未来时间
            if (empty($groupuserRow)){//该用户处于无需考勤人员组中
                $return['code'] = 400;
                $return['msg'] = "该用户没有考勤组,不需要打卡！";

            }elseif (count($groupuserRow)>=2 || in_array(2,$types)){
                $return['code'] = 400;
                $return['msg'] = "该用户不需要打卡！";
            }else {
                $goDaysNum = unserialize($groupuserRow[0]['goDaysNum']);
                $num  = $goDaysNum?count($goDaysNum):1;
                $op = [
                    [
                        'sureTime'=>$goDaysNum[0]['startTime'],
                        'clockinType'=>1,
                        'clockinNum'=>1,
                    ],
                    [
                        'sureTime'=>$goDaysNum[0]['endTime'],
                        'clockinType'=>2,
                        'clockinNum'=>1,
                    ],
                    [
                        'sureTime'=>$goDaysNum[1]['startTime'],
                        'clockinType'=>1,
                        'clockinNum'=>2,
                    ],
                    [
                        'sureTime'=>$goDaysNum[1]['endTime'],
                        'clockinType'=>2,
                        'clockinNum'=>2,
                    ],
                    [
                        'sureTime'=>$goDaysNum[2]['startTime'],
                        'clockinType'=>1,
                        'clockinNum'=>3,
                    ],
                    [
                        'sureTime'=>$goDaysNum[2]['endTime'],
                        'clockinType'=>2,
                        'clockinNum'=>3,
                    ],
                ];
                switch ($num){
                    case 1:
                        unset($op[5]);
                        unset($op[4]);
                        unset($op[3]);
                        unset($op[2]);
                        break;
                    case 2:
                        unset($op[5]);
                        unset($op[4]);
                        break;
                }
                $return['status'] = 5;
                $return['msg'] = "未到打卡时间！";
                $return['data'] = $op;
            }
        }
        return $return;
    }


    /**
     * 获取当前考勤是正常考勤还是外勤考勤 有无外出申请 只针对当天的获取
     * @param $memberId
     * @param $platformId
     * @param $sureTime
     * @return array|bool
     */
    private function appUserIsOutGo($memberId,$platformId,$sureTime,$date=''){
        if (!$date){
            $date = date('Y-m-d',time());
        }
        //把打卡时间点转换日期时间戳
        $time = strtotime($date." ".$sureTime);
        $appoutgorecordCondition = " startTime<={$time} and endTime>={$time} and memberId={$memberId} and status=2 and platformId={$platformId} ";
        $appoutgorecordModel = new model_attendance_appoutgorecord();
        $appoutgorecordRow = $appoutgorecordModel->selectOne($appoutgorecordCondition,'id,address,lng,lat,radius deviation');
        if ($appoutgorecordRow){
            return $appoutgorecordRow;
        }
        return false;
    }

    //用户在某个日期的考勤 缺卡记录添加
    /**
     * @param $recordInfos  @@选择日期的打卡记录
     * @param $clockinNums  @@应打卡次数
     * @param $agId  @@考勤组ID
     * @param $userId  @@用户ID
     */
    public function insertLackCard($recordInfos,$clockinNums,$agId,$userId){
        $attendancerecordModel = new model_attendance_attendancerecord();
        if (($clockinNums*2)!=count($recordInfos)){
            //进行缺卡记录查询
            $yy = [
                1=>"",
                2=>"",
                3=>"",
            ];
            foreach ($recordInfos as $riK=>$riV){
                $yy[$riV['clockinNum']] .= $riV['clockinType'].",";
            }
            switch ($clockinNums){
                case 1:
                    $yy[1] = explode(',',$yy[1]);
                    if (!in_array(1,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }elseif (!in_array(2,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }
                    break;
                case 2:
                    if (!in_array(1,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }elseif (!in_array(2,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }
                    if (!in_array(1,$yy[2])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>2
                        ]);
                    }elseif (!in_array(2,$yy[2])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>2
                        ]);
                    }
                    break;
                case 3:
                    if (!in_array(1,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }elseif (!in_array(2,$yy[1])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>1
                        ]);
                    }
                    if (!in_array(1,$yy[2])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>2
                        ]);
                    }elseif (!in_array(2,$yy[2])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>2
                        ]);
                    }
                    if (!in_array(1,$yy[3])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>1,
                            'no'=>2,
                            'clockinNum'=>3
                        ]);
                    }elseif (!in_array(2,$yy[3])){
                        $attendancerecordModel->insert([
                            'memberId'=>$userId,
                            'agId'=>$agId,
                            'isGo'=>1,
                            'clockinType'=>2,
                            'no'=>2,
                            'clockinNum'=>3
                        ]);
                    }
                    break;
            }
        }
    }

    /**
     * 获取日历状态值返回接口
     */
    public function getCalendarStatusList(AttendanceGroupDTO $attendancegroup){
        $data = $attendancegroup->data ? gdl_lib_BaseUtils::getStr($attendancegroup->data) : "";

        #接受参数

        $date = $data['date']?$data['date']:0;
        $userId = $data['userId']?$data['userId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 200;
        if(empty($userId)){$result->message = "请选择用户"; return $result;}
        if(empty($date)){$result->message = "请选择日期"; return $result;}

//        $result->message = json_encode($data);
//        return $result;

        try{
            // 1时间错误红色 2身份地点错误黄色 3都正确绿色 4没有打卡记录
            $t = time();
            $startTime = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));//获取当天的0点时间戳
            $endTime = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));//获取当天的下午12点时间戳
            $date = strtotime($date);//获取选择日期时间戳
            if ($date<$startTime){//1 今天 2 过去 3未来
                $istoday = 2;
            }elseif ($date>$endTime){
                $istoday = 3;
            }else{
                $istoday = 1;
            }

			$groupmemberrecordModel = new model_attendance_groupmemberrecord();

            $attendancerecord = new model_attendance_attendancerecord();
            $globalsModel = new service_globals();
            $tNum = date("t",$date);//选择日期的天数
            $start_time = strtotime(date('Y-m-01',$date));  //获取本月第一天时间戳
            $array = array();
            for($i=0;$i<$tNum;$i++){
//            $array[] = date('Y-m-d',$start_time+$i*86400); //每隔一天赋值给数组
				$dayTime = $start_time+$i*86400;
                $yMd = date('Y-m-d',$dayTime); //每隔一天赋值给数组
				//休息日start
					$type = 1;//1工作日 2休息日 3未排班
					$groupmemberrecordInfo = $groupmemberrecordModel->selectOne("memberIds like '%$userId%' and addTime<={$dayTime} order by id  desc");

					if (!$groupmemberrecordInfo){//当天没有班次添加
						$type = 3;
					}else{
						$workdayKey = unserialize($groupmemberrecordInfo['workday']);
						$holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
						$specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));
						$unusualStatus     = unserialize($groupmemberrecordInfo['unusualStatus']);//一天上班次数设置及其时间
						//获取日期是否是休息日 bool false是节假日  true不是节假日
						$isHolidaysAndFestivals = $globalsModel->getDateIsHolidaysAndFestivals($yMd,$workdayKey,$holidayKey,$specialWorkdayKey);
						if($isHolidaysAndFestivals){
							$type = 1;
						}else{
							$type = 2;
						}
					}
					//end
                if ($istoday==3){//1 今天 2 过去 3未来
                    $array[] = ['status'=>4,'date'=>$yMd,'type'=>$type];
                }else{
                    //select name, sum(if(score>=60,1,0)),sum(if(score<60,1,0)) from score2 group by name
                    //判断选择日期的打卡时间有没有记录
                    // abnormalIdentityIs人脸验证  abnormalCoordinateIs地点验证 missCard 缺卡  supCard 补卡  leave 请假 field 外勤 late 迟到 leavEarly 早退
                    $lists = $attendancerecord->selectOne("memberId = {$userId} and sureDate = '{$yMd}'","sum(if(abnormalIdentityIs=2,1,0)) as abnormalIdentityIs,sum(if(abnormalCoordinateIs=2,1,0)) as abnormalCoordinateIs,sum(if(no=2,1,0)) as missCard,sum(if(no=3,1,0)) as supCard,sum(if(leaveIn=2,1,0)) as `leave`,sum(if(isGo=2,1,0)) as wQ,sum(if(abnormal=1,1,0)) as late,sum(if(abnormal=2,1,0)) as leavEarly");
				
                    if ($lists['abnormalIdentityIs']==null || (empty($lists['abnormalIdentityIs']) && $lists['abnormalIdentityIs']!=0)){
                        $array[] = ['status'=>4,'date'=>$yMd,'type'=>$type];
                    }else{
                        if ($lists['abnormalCoordinateIs']==0 && $lists['abnormalIdentityIs']==0 && $lists['missCard']==0 && $lists['late']==0 && $lists['leavEarly']==0){
                            $array[] = ['status'=>3,'date'=>$yMd,'type'=>$type];
                        }elseif ( ($lists['late']!=0 || $lists['leavEarly']!=0 || $lists['missCard']!=0)  && $type==1){//节假日不作缺卡或者 时间异常
							//迟到 或者 早退 红色 ，
                            $array[] = ['status'=>1,'date'=>$yMd,'type'=>$type];
                        }else{//身份异常 或者地点异常 但是时间正常 黄色  ($lists['abnormalCoordinateIs']!=0 || $lists['abnormalIdentityIs']!=0))
                            $array[] = ['status'=>2,'date'=>$yMd,'type'=>$type];
                        }
                    }
                }
            }

            $result->data = $array;
            $result->message ='成功';
            $result->code = 200;

        }catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //array [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
    private function arrayDateToKey($array){
        if (!is_array($array))return false;
        $dateArray = [];
        foreach ($array as $key=>$value){
            $dates = explode('?@',$value);
            $dateArray[] =$dates[0];
        }
        return $dateArray;
    }
}
